<template>
  <el-dialog 
    v-model="dialogVisible" 
    title="上传音频" 
    width="500px"
    :before-close="handleClose"
    destroy-on-close>
    
    <el-form :model="uploadForm" label-position="top">
      <el-form-item label="音频文件">
        <el-upload
          ref="audioUploadRef"
          class="audio-uploader"
          :auto-upload="false"
          :limit="1"
          accept="audio/*"
          :on-change="handleAudioChange"
          :on-remove="handleAudioRemove">
          <el-button type="primary">选择音频文件</el-button>
          <template #tip>
            <div class="el-upload__tip">支持多种音频格式</div>
          </template>
        </el-upload>
      </el-form-item>
      
      <el-form-item label="字幕文件 (可选)">
        <el-upload
          ref="subtitleUploadRef"
          class="subtitle-uploader"
          :auto-upload="false"
          :limit="1"
          accept=".srt,.vtt,.ass"
          :on-change="handleSubtitleChange"
          :on-remove="handleSubtitleRemove">
          <el-button>选择字幕文件</el-button>
          <template #tip>
            <div class="el-upload__tip">支持 SRT、VTT、ASS 格式</div>
          </template>
        </el-upload>
      </el-form-item>
      
      <el-form-item label="目标目录 (可选)">
        <el-input v-model="uploadForm.directory" placeholder="输入目标目录路径"></el-input>
      </el-form-item>
      
      <el-form-item label="组ID (可选)">
        <el-input v-model="uploadForm.groupId" placeholder="输入组ID"></el-input>
      </el-form-item>
      
      <el-form-item label="排序 (可选)">
        <el-input-number v-model="uploadForm.order" :min="0" :step="1" step-strictly></el-input-number>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="uploading" @click="submitUpload">上传</el-button>
      </span>
    </template>
    
    <el-dialog v-model="uploadResultVisible" title="上传结果" width="30%" append-to-body>
      <div v-if="uploadResult.success" class="success-message">
        <el-icon class="success-icon"><check /></el-icon>
        <p>上传成功</p>
      </div>
      <div v-else class="error-message">
        <el-icon class="error-icon"><close /></el-icon>
        <p>{{ uploadResult.message || '上传失败' }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeResultDialog">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { defineComponent, ref, reactive, watch } from 'vue';
import mergeService from '../services/mergeService';
import { Check, Close } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

export default defineComponent({
  name: 'AudioUploader',
  
  components: {
    Check,
    Close
  },
  
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    // 可以接收默认组ID
    defaultGroupId: {
      type: String,
      default: ''
    }
  },
  
  emits: ['update:visible', 'upload-success'],
  
  setup(props, { emit }) {
    // 对话框状态
    const dialogVisible = ref(false);
    
    // 监听props.visible变化来控制对话框显示
    watch(() => props.visible, (newVal) => {
      dialogVisible.value = newVal;
      
      // 如果对话框开启，设置默认组ID
      if (newVal && props.defaultGroupId) {
        uploadForm.groupId = '';
      }
    });
    
    // 监听dialogVisible变化来通知父组件
    watch(dialogVisible, (newVal) => {
      emit('update:visible', newVal);
    });
    
    // 引用和状态
    const audioUploadRef = ref(null);
    const subtitleUploadRef = ref(null);
    const uploading = ref(false);
    const uploadResultVisible = ref(false);
    
    const uploadForm = reactive({
      directory: '',
      groupId: props.defaultGroupId || '',
      order: 0,
      metaData: {}
    });
    
    const uploadResult = reactive({
      success: false,
      message: ''
    });
    
    // 文件状态
    const audioFile = ref(null);
    const subtitleFile = ref(null);
    
    // 处理文件变化
    const handleAudioChange = (file) => {
      audioFile.value = file.raw;
    };
    
    const handleSubtitleChange = (file) => {
      subtitleFile.value = file.raw;
    };
    
    const handleAudioRemove = () => {
      audioFile.value = null;
    };
    
    const handleSubtitleRemove = () => {
      subtitleFile.value = null;
    };
    
    // 关闭对话框
    const handleClose = () => {
      dialogVisible.value = false;
    };
    
    // 关闭结果对话框
    const closeResultDialog = () => {
      uploadResultVisible.value = false;
      
      // 如果上传成功，关闭主对话框
      if (uploadResult.success) {
        dialogVisible.value = false;
      }
    };
    
    // 提交上传
    const submitUpload = async () => {
      if (!audioFile.value) {
        ElMessage.warning('请选择音频文件');
        return;
      }
      
      try {
        uploading.value = true;
        
        const options = {
          directory: uploadForm.directory || undefined,
          groupId: uploadForm.groupId || undefined,
          order: uploadForm.order || 0,
          metaData: uploadForm.metaData || {}
        };
        
        const response = await mergeService.uploadAudio(
          audioFile.value, 
          subtitleFile.value, 
          options
        );
        
        // 处理响应
        uploadResult.success = response.success;
        uploadResult.message = response.message;
        uploadResultVisible.value = true;
        
        // 重置表单
        if (response.success) {
          audioUploadRef.value.clearFiles();
          if (subtitleUploadRef.value) {
            subtitleUploadRef.value.clearFiles();
          }
          audioFile.value = null;
          subtitleFile.value = null;
          
          // 通知父组件上传成功
          emit('upload-success', response.data);
        }
      } catch (error) {
        console.error('上传失败:', error);
        uploadResult.success = false;
        uploadResult.message = error.message || '上传失败，请稍后再试';
        uploadResultVisible.value = true;
      } finally {
        uploading.value = false;
      }
    };
    
    return {
      dialogVisible,
      audioUploadRef,
      subtitleUploadRef,
      uploading,
      uploadForm,
      uploadResult,
      uploadResultVisible,
      handleAudioChange,
      handleSubtitleChange,
      handleAudioRemove,
      handleSubtitleRemove,
      submitUpload,
      handleClose,
      closeResultDialog
    };
  }
});
</script>

<style scoped>
.success-message, .error-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.success-icon {
  font-size: 48px;
  color: #67C23A;
  margin-bottom: 10px;
}

.error-icon {
  font-size: 48px;
  color: #F56C6C;
  margin-bottom: 10px;
}

.audio-uploader, .subtitle-uploader {
  display: block;
}
</style>